const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path')
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin')
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')

const srcFiles = glob.sync('./src/**/*.jsx');
const entries = {};

srcFiles.forEach(entry => {
    let name = entry.replace('./src/', '').replace('.jsx', '');
    entries[name] = entry;
});

const htmls = srcFiles.map(entry => {
    let name = entry.replace('./src/', '').replace('.jsx', '');
    return new HtmlWebPackPlugin({
        filename: `${name}.html`,
        template: 'public/index.html',
        chunks: [ name ]
    })
});
module.exports = {
    entry: entries,
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'js/[name].js',
        // publicPath:'http://localhost:8181/',         //同样可以
        publicPath: '/',
        //chunkFilename: "js/[name].bundle.min.js?ver=[chunkhash]"
    },
    resolve: {
        extensions: ['.wasm', '.mjs', '.js', '.json', '.jsx']
    },
    devServer: {
        contentBase: path.join(__dirname, './dist'),
        publicPath: '/',
        host: '127.0.0.1',
        port: 3000,
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/, // jsx/js文件的正则
                exclude: /node_modules/, // 排除 node_modules 文件夹
                use: {
                    // loader 是 babel
                    loader: 'babel-loader',
                    options: {
                        // babel 转义的配置选项
                        babelrc: false,
                        presets: [
                            // 添加 preset-react
                            require.resolve('@babel/preset-react'),
                            [require.resolve('@babel/preset-env'), {modules: false}]
                        ],
                        cacheDirectory: true
                    }
                }
            },
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader'],
            },
        ]
    },
    optimization: {
        // splitChunks:{
        //     chunks: 'all',
        // },
        minimizer: [
            // 用于优化css文件
            new OptimizeCssAssetsPlugin({
                assetNameRegExp: /\.css$/g,
                cssProcessorOptions: {
                    safe: true,
                    autoprefixer: {disable: true},
                    mergeLonghand: false,
                    discardComments: {
                        removeAll: true // 移除注释
                    }
                },
                canPrint: true
            })
        ]
    },
    plugins: [
        new MiniCssExtractPlugin()
    ].concat(htmls)
};
